﻿using System;
using System.Collections.Generic;
using System.Text;
using AccountManager.TableModel.Model;
using AccountManager.AL.Enums;
using AccountManager.Runtime;

namespace AccountManager.AL
{
    public class ALZhangHuDuiZhang : ALBase
    {
        /// <summary>
        /// 账户对账
        /// </summary>
        public bool VerifyAccount(string accountId,string consumeTypeId,decimal newBalance, out string errMsg)
        {
            errMsg = null;
            try
            {
                TAccount sourceModel = DA.GetModel<TAccount>(accountId);
                if (sourceModel.Balance == newBalance)
                {
                    errMsg = "原余额与现余额相等不需要对账!";
                    return false;
                }
                DA.TransStart();
                decimal verifyAmount = newBalance - sourceModel.Balance;
                EnBalanceType balanctType;
                TConsume consumeModel = new TConsume();
                if (verifyAmount > 0)
                {
                    balanctType = EnBalanceType.DuiZhangShouRu;
                    consumeModel.ConsumeName = "对账收入";
                }
                else
                {
                    balanctType = EnBalanceType.DuizhangZhiChu;
                    consumeModel.ConsumeName = "对账支出";
                }

                consumeModel.Id = GetGuid();
                //注意:将选择账目类型放到Remark里了
                consumeModel.ConsumeTypeId = consumeTypeId;
                consumeModel.AccountId = accountId;
                consumeModel.AddTime = GetNowTime();
                consumeModel.Amount = verifyAmount;
                consumeModel.Balance = sourceModel.Balance + verifyAmount;
                consumeModel.ConsumeDate = GetNowTime();
                consumeModel.BalanceTypeId = ((int)balanctType);
                consumeModel.IsCancel = false;
                consumeModel.LastTime = GetNowTime();
                consumeModel.OperatorId = LoginInfo.OperatorId;
                DA.Add(consumeModel);

                sourceModel.Balance = sourceModel.Balance + verifyAmount;
                sourceModel.UseCount += 1;
                sourceModel.LastTime = GetNowTime();
                DA.Update(sourceModel, TAccount.CNLastTime, TAccount.CNBalance);

                DA.TransCommit();
                return true;
            }
            catch (Exception ex)
            {
                DA.TransRollback();
                errMsg = ex.Message;
                return false;
            }
        }
    }
}
